import { useMount, useSetState } from "react-use";
import { ResBody, request } from "../common/request";
import { CashoutModel, StatsModel } from "../common/model";
import {
  Badge,
  Button,
  Descriptions,
  Divider,
  Form,
  Input,
  InputNumber,
  Modal,
  Spin,
} from "antd";
import dayjs from "dayjs";
import InfiniteScroll, {
  InfiniteScrollLoading,
} from "../components/InfiniteScroll";
import { useCallback } from "react";
import { useSystemStore } from "../store/system";

const Settlement: React.FC = () => {
  const [form] = Form.useForm();
  const system = useSystemStore();
  const [state, setState] = useSetState({
    stats: undefined as StatsModel | undefined,
    statsLoading: false,
    cashOpen: false,
    cashData: [] as CashoutModel[],
    cashLoading: false as InfiniteScrollLoading,
    page: 1,
    total: -1,
  });

  const loadStats = async () => {
    setState({ statsLoading: true });
    const ret = await request.get<ResBody>("/api/cashout/stats");

    if (ret.data.code === 200) {
      setState({ stats: ret.data.result, statsLoading: false });
    } else {
      setState({ statsLoading: false });
    }
  };

  useMount(async () => {
    await loadStats();
    next(true);
  });

  const next = useCallback(
    async (init?: boolean) => {
      setState({ cashLoading: "reload" });
      const ret = await request.get<ResBody>("/api/cashout", {
        params: {
          page: init ? 1 : state.page,
          page_size: 10,
        },
      });
      if (ret.data.code === 200) {
        setState((e) => ({
          cashData: init ? ret.data.result : e.cashData.concat(ret.data.result),
          cashLoading: false,
          page: init ? 2 : state.page + 1,
          total: ret.data.info?.total,
        }));
      } else {
        setState({ cashLoading: false });
      }
    },
    [state.page]
  );

  const onFinish = async () => {
    const body = await form.validateFields();
    const ret = await request.post<ResBody>(
      "/api/cashout/create",
      JSON.stringify({
        amount: body.amount,
        mark: body.mark,
        pre_balance: state.stats?.unCashout,
      })
    );

    if (ret.data.code === 200) {
      system.message("success", ret.data.result);
      setState({ cashOpen: false });
      loadStats();
      next(true);
    }
  };

  return (
    <Spin spinning={state.statsLoading}>
      <Modal
        centered
        title="发起提现"
        open={state.cashOpen}
        okText="确认"
        cancelText="取消"
        onCancel={() => setState({ cashOpen: false })}
        onOk={onFinish}
      >
        <Form form={form} className="py-8">
          <Form.Item
            name="amount"
            label="提现金额"
            initialValue={1.0}
            rules={[
              { required: true, message: "请输入提现金额" },
              {
                validator(_, value) {
                  if (value > state.stats?.unCashout!) {
                    return Promise.reject("不能超过未提现余额");
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <InputNumber size="large" precision={2} className="min-w-full" />
          </Form.Item>
          <Form.Item
            name="mark"
            label="备注"
            rules={[{ required: true, message: "请输入备注" }]}
          >
            <Input.TextArea size="large" maxLength={100} showCount />
          </Form.Item>
        </Form>
      </Modal>
      <div className="text-4xl">当前总收入：{state.stats?.income}</div>
      <div className="text-4xl">当前未提现：{state.stats?.unCashout}</div>
      <Divider />
      <Button
        size="large"
        type="primary"
        onClick={() => setState({ cashOpen: true })}
      >
        发起提现
      </Button>
      <InfiniteScroll
        loading={state.cashLoading}
        next={next}
        hasMore={state.total - state.cashData.length > 0}
        threshold={50}
        total={state.total}
      >
        {state.cashData.map((v) => (
          <Descriptions
            bordered
            className="mt-4"
            size="small"
            key={v.id}
            items={[
              {
                key: "1",
                label: "提现日期",
                children: dayjs(v.create_at).format("DD/MM/YYYY HH:mm:ss"),
              },
              {
                key: "2",
                label: "提现金额",
                children: v.amount,
              },
              {
                key: "3",
                label: "提现状态",
                children: (
                  <Badge
                    color="green"
                    status={
                      v.status === "progress" ? "processing" : "processing"
                    }
                    text="进行中"
                  />
                ),
              },
              {
                key: "5",
                label: "当前余额",
                children: v.pre_balance,
              },
              {
                key: "5",
                label: "提现后余额",
                children: v.after_balance,
              },
              {
                key: "6",
                label: "备注",
                children: <>{v.mark}</>,
              },
            ]}
          />
        ))}
      </InfiniteScroll>
    </Spin>
  );
};

export default Settlement;
